package com.itaming.lycheeframework.core.config;

import com.itaming.lycheeframework.core.properties.LycheeExecutorProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.SchedulingTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Executor配置类
 *
 * @author A.Ming
 */
@AutoConfiguration
@EnableAsync
@EnableConfigurationProperties({LycheeExecutorProperties.class})
@EnableScheduling
@RequiredArgsConstructor
public class ExecutorConfiguration {

    /**
     * Async配置参数
     */
    private final LycheeExecutorProperties executorProperties;

    /**
     * 异步任务线程池
     */
    @Bean(name = "asyncTaskExecutor")
    public AsyncTaskExecutor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(executorProperties.getAsync().getCorePoolSize());
        executor.setMaxPoolSize(executorProperties.getAsync().getMaxPoolSize());
        executor.setQueueCapacity(executorProperties.getAsync().getQueueCapacity());
        executor.setKeepAliveSeconds(executorProperties.getAsync().getKeepAliveSeconds());
        executor.setThreadNamePrefix(executorProperties.getAsync().getThreadNamePrefix());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    /**
     * 定时任务线程池
     */
    @Bean(name = "schedulingTaskExecutor")
    public SchedulingTaskExecutor schedulingTaskExecutor() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(executorProperties.getScheduling().getPoolSize());
        executor.setThreadNamePrefix(executorProperties.getScheduling().getThreadNamePrefix());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

}
